package org.ichamigua.user.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.ichamigua.user.mapper.UserMapper;
import org.ichamigua.user.service.UserService;
import org.ichamigua.user.service.UserUpdateAvatarLogService;
import org.ichamigua.user.service.UserUpdateNicknameLogService;
import org.ichamigua.user.service.UserUpdateUsernameLogService;
import org.ichihamigua.common.framework.entity.Result;
import org.ichihamigua.common.qiniucloud.service.QiniuObjectStoreService;
import org.ichihamigua.common.qiniucloud.vo.UploadFileVo;
import org.ichihamigua.common.user.dto.UpdateAvatarLogDto;
import org.ichihamigua.common.user.dto.UpdateNicknameDto;
import org.ichihamigua.common.user.dto.UpdateUsernameDto;
import org.ichihamigua.common.user.entity.UserEntity;
import org.ichihamigua.common.user.entity.UserUpdateAvatarLogEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author zzy
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    private final static String USER_AVATAR_FILE_BUCKET_NAME = "ichihamigua";

    @Resource
    private QiniuObjectStoreService qiniuObjectStoreService;

    @Resource
    private UserUpdateAvatarLogService userUpdateAvatarLogService;

    @Resource
    private UserUpdateUsernameLogService userUpdateUsernameLogService;

    @Resource
    private UserUpdateNicknameLogService userUpdateNicknameLogService;



    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Result<?> updateAvatar(Long userId, MultipartFile file) {

        //查询用户修改次数
        if(userUpdateAvatarLogService.countMonthAvatarUpdate(userId) >= 3){
            return Result.fail("本月修改头像次数已上限");
        }

        //上传头像
        Result<UploadFileVo> upload = qiniuObjectStoreService.upload(
                USER_AVATAR_FILE_BUCKET_NAME,
                String.format("avatar-%d-%d.jpg", userId, System.currentTimeMillis()),
                file
        );
        if(!upload.getSuccess()){
            return upload;
        }
        String url = "ic_avatar://"+upload.getData().getFileName();

        //修改头像、添加修改记录
        UserEntity user = new UserEntity();
        user.setId(userId);
        user.setAvatarUrl(url);
        if (!save(user) || !userUpdateAvatarLogService.addLog(userId, url)){
            return Result.fail("修改失败");
        }
        return Result.success();
    }

    /**
     * 查询用户
     * @param userId 用户ID
     * @param columns 查询的字段
     * @return 查出该用户指定的用户字段
     */
    @Override
    public UserEntity getOne(Long userId, List<SFunction<UserEntity, ?>> columns){
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserEntity::getId, userId);
        if(columns != null ) wrapper.select(columns);
        return getOne(wrapper);
    }

    /**
     * 查询用户
     * @param userId 用户ID
     * @return 查出该用户所有的字段
     */
    @Override
    public UserEntity getOne(Long userId){
        return getOne(userId, null);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Result<?> updateUsername(Long userId, UpdateUsernameDto dto) {
        //查询用户修改次数
        if(userUpdateUsernameLogService.countYearUsernameUpdate(userId) >= 1){
            return Result.fail("本年修改头像次数已上限");
        }
        //修改用户名、添加修改记录
        String username = dto.getValue();
        UserEntity user = new UserEntity();
        user.setId(userId);
        user.setUsername(username);
        if (!save(user) || !userUpdateUsernameLogService.addLog(userId, username)){
            return Result.fail("修改失败");
        }
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Result<?> updateNickname(Long userId, UpdateNicknameDto dto) {
        //查询用户修改次数
        if(userUpdateNicknameLogService.countMonthNicknameUpdate(userId) >= 3){
            return Result.fail("本月修改昵称次数已上限");
        }
        //修改昵称、添加修改记录
        String nickname = dto.getValue();
        UserEntity user = new UserEntity();
        user.setId(userId);
        user.setNickname(nickname);
        if (!save(user) || !userUpdateNicknameLogService.addLog(userId, nickname)){
            return Result.fail("修改失败");
        }
        return Result.success();

    }

    @Override
    public Result<?> updateBeforeAvatar(Long userId, UpdateAvatarLogDto dto) {
        String avatar = dto.getValue();
        UserEntity user = new UserEntity();
        user.setId(userId);
        user.setAvatarUrl(avatar);
        if(!save(user)){
            return Result.fail("修改失败");
        }
        return Result.success();
    }



}
